package com.net.wanjian.networkhospitalmanager.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.activity.base.BaseActivity;
import com.net.wanjian.networkhospitalmanager.adapter.FirstListDepartmentAdapter;
import com.net.wanjian.networkhospitalmanager.adapter.SecondListDepartmentAdapter;
import com.net.wanjian.networkhospitalmanager.adapter.VoidListAdapterX;
import com.net.wanjian.networkhospitalmanager.adapter.base.RecyclerBaseAdapter;
import com.net.wanjian.networkhospitalmanager.bean.Video.GetVideoClassifyBean;
import com.net.wanjian.networkhospitalmanager.bean.Video.GetVideoListBean;
import com.net.wanjian.networkhospitalmanager.bean.teacherevent.DepartmentListResult;
import com.net.wanjian.networkhospitalmanager.consts.ErrorCodeReturn;
import com.net.wanjian.networkhospitalmanager.net.HttpUtil;
import com.net.wanjian.networkhospitalmanager.netstatus.NetUtils;
import com.net.wanjian.networkhospitalmanager.utils.SharedXmlUtil;
import com.net.wanjian.networkhospitalmanager.utils.ToastUtil;
import com.net.wanjian.networkhospitalmanager.utils.URLDecoderUtil;
import com.net.wanjian.networkhospitalmanager.view.LPopupWindow;
import com.net.wanjian.networkhospitalmanager.widge.RefreshRecyclerView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.UUID;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import butterknife.BindView;
import io.reactivex.observers.DisposableObserver;

/**
 * Created by WJ on 2017/8/14.
 */

public class VideoPlaybackActivity extends BaseActivity implements View.OnClickListener {
    private String WJ_Home_AccessKey = "LTAIPuR8IfTyWIan";
    private String WJ_Home_AccessSecret = "PW0mx2aGuhGhYHj7qeXtisQ9Skjbvq";
    private String playKey = "ex491ux1dof8qnpu2n99k88n9uphb4kyr4wgq62ws1dawxcnusthjgfob935838t";
    private static final String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    //方便测试S
    private String CateId = "274011476";
    final String HTTP_METHOD = "GET";
    final String SEPARATOR = "&";
    final String EQUAL = "=";
    private static final String ENCODE_TYPE = "UTF-8";
    private String Timestamp = formatIso8601Date(new Date());
    private String SignatureNonce = UUID.randomUUID().toString();
    private ArrayList<GetVideoListBean.VideoListBean.VideoBean> videoList;
    private ArrayList<GetVideoListBean.VideoListBean.VideoBean> videoBeansX;
    private VoidListAdapterX voidListAdapterX;
    @BindView(R.id.top_back_text_tv)
    TextView topBackTextTv;
    @BindView(R.id.teacher_event_department_name_tv)
    TextView teacherEventDepartmentNameTv;
    @BindView(R.id.teacher_event_department_name_iv)
    ImageView teacherEventDepartmentNameIv;
    @BindView(R.id.teacher_event_department_layout)
    RelativeLayout teacherEventDepartmentLayout;
    @BindView(R.id.teacher_event_department_relative)
    RelativeLayout mDepartmentRelativeLayout;
    @BindView(R.id.top_back_layout)
    LinearLayout topBackLayout;
    @BindView(R.id.top_title_tv)
    TextView topTitleTv;
    @BindView(R.id.recycler_void_list)
    RefreshRecyclerView recyclerVoidList;
    //=====复用=====
    private LPopupWindow mPopupWindow;
    private ListView leftListView;
    private ListView rightListView;
    private final String FIRST_POS_KEY = "first_po_key";
    private final String SECOND_POS_KEY = "second_pos_key";
    private List<DepartmentListResult.DataBean.DepartmentListBean> mFirstList;
    private List<DepartmentListResult.DataBean.DepartmentListBean.SecondDepartmentListBean> mSecondList;
    //private String CateId;

    @Override
    protected void initData() {
        videoList = new ArrayList<>();
        videoBeansX = new ArrayList<>();
        topTitleTv.setText("视频播放列表");
      //  CateId = SharedXmlUtil.getInstance().getVideoId();
       // Log.e("XXX", CateId );
        LocalData();
        GetVideoClassify(CateId); //获取视频分类
        GetVideoList(); //获取视频列表
        PutData(); //添加数据
        EventClick();

    }

    private void EventClick() {
        teacherEventDepartmentLayout.setOnClickListener(this);
        topBackLayout.setOnClickListener(this);
    }

    private void LocalData() {
        topBackTextTv.setVisibility(View.GONE);
        GridLayoutManager mLayoutManager = new GridLayoutManager(VideoPlaybackActivity.this, 2, GridLayoutManager.VERTICAL, false);
        recyclerVoidList.setLayoutManager(mLayoutManager);
        mFirstList = new ArrayList<>();
        //本地模拟数据 加载listview的
        // 初始化默认医院选择为0，全部
        SharedXmlUtil.getInstance().write(FIRST_POS_KEY, 0);
        SharedXmlUtil.getInstance().write(SECOND_POS_KEY, 0);
        mFirstList = new ArrayList<>();

        List<DepartmentListResult.DataBean.DepartmentListBean.SecondDepartmentListBean> m2List;
        m2List = new ArrayList<>();
        DepartmentListResult.DataBean.DepartmentListBean d = new DepartmentListResult.DataBean.DepartmentListBean();
        d.setDepartmentID("0");
        d.setDepartmentName("科室");

        DepartmentListResult.DataBean.DepartmentListBean.SecondDepartmentListBean b = new DepartmentListResult.DataBean.DepartmentListBean.SecondDepartmentListBean();
        b.setDepartmentID("0");
        b.setDepartmentName("全部科室");
        m2List.add(b);
        d.setSecondDepartmentList(m2List);
        mFirstList.add(d);
        //获取科室列表
        getDepartmentListHttpRequest();
        recyclerVoidList.setRefreshMode(1);
        recyclerVoidList.addOnRefreshListener(new RefreshRecyclerView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                GetVideoList();
                recyclerVoidList.refreshComplete();
            }

            @Override
            public void onLoadMore() {

            }
        });

    }

    private void PutData() {
        voidListAdapterX = new VoidListAdapterX(this);
        voidListAdapterX.setList(videoBeansX);
        recyclerVoidList.setAdapter(this.voidListAdapterX);
        voidListAdapterX.setOnItemClickListener(new RecyclerBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int pos) {
                String videoId = videoBeansX.get(pos).getVideoId();
                Intent intent = new Intent(VideoPlaybackActivity.this, SkinActivity.class);
                intent.putExtra("vid", videoId);
                intent.putExtra("keyid", WJ_Home_AccessKey);
                intent.putExtra("secret", WJ_Home_AccessSecret);
                intent.putExtra("playKey", playKey);
                intent.putExtra("type", "datasource");
                startActivity(intent);
            }
        });

    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_void_list;
    }

    private void GetVideoClassify(String cateId) {
        Map<String, String> parameterMap = new HashMap<String, String>();
        //TODO 加入请求公共参数
        parameterMap.put("Format", "JSON");
        parameterMap.put("Version", "2017-03-21");
        parameterMap.put("SignatureMethod", "HMAC-SHA1");
        parameterMap.put("SignatureVersion", "1.0");
        parameterMap.put("AccessKeyId", WJ_Home_AccessKey);
        parameterMap.put("Timestamp", Timestamp);
        parameterMap.put("SignatureNonce", SignatureNonce);
        parameterMap.put("Action", "GetCategories");
        parameterMap.put("PageNo", "1");
        parameterMap.put("PageSize", "10");
        parameterMap.put("CateId", cateId);
        List<String> sortedKeys = new ArrayList<String>(parameterMap.keySet());
        Collections.sort(sortedKeys);
        //开始生成签名
        String PuR8IfTyWIan = GoToSign(sortedKeys, parameterMap);
        //请求视频分类
        HttpUtil.GetVideoClassifyX(PuR8IfTyWIan, "JSON", "2017-03-21", "HMAC-SHA1",
                "1.0", WJ_Home_AccessKey, Timestamp, SignatureNonce, "GetCategories", "1", "10", cateId, new DisposableObserver<GetVideoClassifyBean>() {
                    @Override
                    public void onNext(GetVideoClassifyBean getVideoClassifyBean) {
                        String cateName = getVideoClassifyBean.getCategory().getCateName();

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void GetVideoList() {
        Map<String, String> parameterMapX = new HashMap<String, String>();
        parameterMapX.put("Format", "JSON");
        parameterMapX.put("Version", "2017-03-21");
        parameterMapX.put("SignatureMethod", "HMAC-SHA1");
        parameterMapX.put("SignatureVersion", "1.0");
        parameterMapX.put("AccessKeyId", WJ_Home_AccessKey);
        parameterMapX.put("Timestamp", Timestamp);
        parameterMapX.put("SignatureNonce", SignatureNonce);
        parameterMapX.put("Action", "GetVideoList");
        parameterMapX.put("PageNo", "1");
        parameterMapX.put("PageSize", "10");
        parameterMapX.put("CateId", CateId);
        List<String> sortedKeys = new ArrayList<String>(parameterMapX.keySet());
        Collections.sort(sortedKeys);
        //开始生成签名
        String PuR8IfTyWIan = GoToSign(sortedKeys, parameterMapX);
        //获取视频列表
        HttpUtil.GetVideoListX(PuR8IfTyWIan, "JSON", "2017-03-21", "HMAC-SHA1",
                "1.0", WJ_Home_AccessKey, Timestamp, SignatureNonce, "GetVideoList", "1", "10", CateId, new DisposableObserver<GetVideoListBean>() {
                    @Override
                    public void onNext(GetVideoListBean getVideoListBean) {
                        List<GetVideoListBean.VideoListBean.VideoBean> video = getVideoListBean.getVideoList().getVideo();
                        videoList.addAll(video);
                        videoBeansX.addAll(video);
                        voidListAdapterX.notifyDataSetChanged();
                        recyclerVoidList.refreshComplete();

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private String GoToSign(List<String> sortedKeys, Map<String, String> parameterMap) {
        StringBuilder stringToSign = new StringBuilder();
        stringToSign.append(HTTP_METHOD).append(SEPARATOR);
        stringToSign.append(percentEncode("/")).append(SEPARATOR);
        StringBuilder QueryString = new StringBuilder();
        for (String key : sortedKeys) {
            // 此处需要对key和value进行编码
            String value = parameterMap.get(key);
            QueryString.append(SEPARATOR).append(percentEncode(key)).append(EQUAL).append(percentEncode(value));
        }
        StringBuilder append = stringToSign.append(percentEncode(QueryString.toString().substring(1)));
        String PuR8IfTyWIan = hmac_sha1(WJ_Home_AccessSecret + "&", append.toString()).trim();
        return PuR8IfTyWIan;
    }


    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    //计算ISO8601时间方法
    private static String formatIso8601Date(Date date) {
        SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT);
        df.setTimeZone(new SimpleTimeZone(0, "GMT"));
        return df.format(date);
    }

    //转码工具类
    private static String percentEncode(String value) {
        if (value == null) return null;
        try {
            return URLEncoder.encode(value, ENCODE_TYPE).replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return value;
    }

    //hmac_sha1算法
    private String hmac_sha1(String key, String datas) {
        String reString = "";

        try {
            byte[] data = key.getBytes("UTF-8");
            //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
            SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
            //生成一个指定 Mac 算法 的 Mac 对象
            Mac mac = Mac.getInstance("HmacSHA1");
            //用给定密钥初始化 Mac 对象
            mac.init(secretKey);

            byte[] text = datas.getBytes("UTF-8");
            //完成 Mac 操作
            byte[] text1 = mac.doFinal(text);

            reString = Base64.encodeToString(text1, Base64.DEFAULT);

        } catch (Exception e) {
            // TODO: handle exception
        }

        return reString;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_back_layout:
                finish();
                break;
            case R.id.teacher_event_department_layout:
                initPopupWindow();
                break;
        }
    }

    private void initPopupWindow() {
        mPopupWindow = new LPopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.popup_window_teacher_event, null);
        leftListView = (ListView) view.findViewById(R.id.popup_window_teacher_event_listview_left);
        rightListView = (ListView) view.findViewById(R.id.popup_window_teacher_event_listview_right);
        View transView = view.findViewById(R.id.popup_trans_view);

//       将view添加到popup里面
        mPopupWindow.setContentView(view);
        mPopupWindow.setBackgroundDrawable(new PaintDrawable(Color.TRANSPARENT));
        mPopupWindow.setFocusable(true);
        //popupWindow消失的监听
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                teacherEventDepartmentNameIv.setSelected(false);
            }
        });
        transView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });
        //获取当前选择的科室
        final int position1 = SharedXmlUtil.getInstance().read(FIRST_POS_KEY, 0);
        final int position2 = SharedXmlUtil.getInstance().read(SECOND_POS_KEY, 0);

        //加载一级分类
        final FirstListDepartmentAdapter firstAdapter = new FirstListDepartmentAdapter(this, mFirstList);
        firstAdapter.setSelectedPosition(position1);
        leftListView.setAdapter(firstAdapter);

        //加载左侧第一行对应右侧二级分类
        mSecondList = new ArrayList<>();
        /**
         * 这里有为null的bug
         */
        mSecondList.addAll(mFirstList.get(position1).getSecondDepartmentList());
        final SecondListDepartmentAdapter secondAdapter = new SecondListDepartmentAdapter(this, mSecondList);
        secondAdapter.setSelectedPosition(position2);
        rightListView.setAdapter(secondAdapter);
        //左侧ListView点击事件
        leftListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //二级数据
                List<DepartmentListResult.DataBean.DepartmentListBean.SecondDepartmentListBean> list2 = mFirstList.get(position).getSecondDepartmentList();
                //如果没有二级类，则直接跳转
                if (list2 == null || list2.size() == 0) {
                    mPopupWindow.dismiss();
                    String firstId = mFirstList.get(position).getDepartmentID();
                    String selectedName = mFirstList.get(position).getDepartmentName();
                    handleResult(firstId, "-1", selectedName);
                    return;
                }

                //如果有二级联动的数据,那么更新数据
                FirstListDepartmentAdapter adapter = (FirstListDepartmentAdapter) (parent.getAdapter());
                //如果上次点击的就是这一个item，则不进行任何操作
                if (adapter.getSelectedPosition() == position) {
                    return;
                }

                //根据左侧一级分类选中情况，更新背景色
                adapter.setSelectedPosition(position);
                adapter.notifyDataSetChanged();

                //显示右侧二级分类
                updateSecondListView(list2, secondAdapter, position, position1, position2);
            }

        });
        //右侧ListView点击事件
        rightListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //关闭popupWindow，显示用户选择的分类
                mPopupWindow.dismiss();
                //videoList.clear();
                String decoder2 = URLDecoderUtil.getDecoder(mSecondList.get(position).getDepartmentName());
                String decoder1 = URLDecoderUtil.getDecoder(mSecondList.get(0).getDepartmentName());
                videoBeansX.clear();
                if (decoder2.equals("全部科室")) {
                    videoBeansX.addAll(videoList);
                    voidListAdapterX.setList(videoBeansX);
                    voidListAdapterX.notifyDataSetChanged();
                } else {
                    if (position == 0) {
                        for (int i = 0; i < videoList.size(); i++) {
                            String Ta = videoList.get(i).getTags();
                            String tags = Ta.split(",")[0];
                            if (decoder1.contains(tags)) {
                                videoBeansX.add(videoList.get(i));
                            }
                        }
                    } else {
                        for (int i = 0; i < videoList.size(); i++) {
                            String Ta = videoList.get(i).getTags();
                            if (Ta.contains(decoder2)) {
                                videoBeansX.add(videoList.get(i));
                            }
                        }

                    }
                    voidListAdapterX.setList(videoBeansX);
                    voidListAdapterX.notifyDataSetChanged();

                }

                int firstPosition = firstAdapter.getSelectedPosition();
                //在这里保存选择的id
                SharedXmlUtil.getInstance().write(FIRST_POS_KEY, firstPosition);
                SharedXmlUtil.getInstance().write(SECOND_POS_KEY, position);
                String firstId = mFirstList.get(firstPosition).getDepartmentID();
                String secondId = mFirstList.get(firstPosition).getSecondDepartmentList().get(position).getDepartmentID();
                String selectedName = mFirstList.get(firstPosition).getSecondDepartmentList().get(position).getDepartmentName();
                //根据右侧二级分类选中情况，更新背景色
                SecondListDepartmentAdapter adapter = (SecondListDepartmentAdapter) parent.getAdapter();
                adapter.setSelectedPosition(position);
                adapter.setFirstPosition(firstPosition);
                adapter.notifyDataSetChanged();

                handleResult(firstId, secondId, selectedName);
            }
        });
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                teacherEventDepartmentNameIv.setSelected(false);

            }
        });

        //最后显示popupwindow
        if (mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        } else {
//         在那个控件下面显示
            teacherEventDepartmentNameIv.setSelected(true);
            mPopupWindow.showAsDropDown(mDepartmentRelativeLayout);
        }

    }

    private void updateSecondListView(List<DepartmentListResult.DataBean.DepartmentListBean.SecondDepartmentListBean> list2, SecondListDepartmentAdapter secondAdapter, int position, int position1, int position2) {
        mSecondList.clear();
        mSecondList.addAll(list2);
        secondAdapter.setFirstCurrentPosition(position);
        secondAdapter.setFirstPosition(position1);
        secondAdapter.setSelectedPosition(position2);
        secondAdapter.notifyDataSetChanged();
    }

    private void handleResult(String firstId, String secondId, String selectedName) {
        teacherEventDepartmentNameTv.setText(URLDecoderUtil.getDecoder(selectedName));
    }

    private void getDepartmentListHttpRequest() {
        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.getDepartmentList(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(), new DisposableObserver<DepartmentListResult>() {
            @Override
            public void onNext(DepartmentListResult departmentListResult) {
                if (departmentListResult.getResult() == ErrorCodeReturn.success) {

                    List<DepartmentListResult.DataBean.DepartmentListBean> departmentList = departmentListResult.getData().getDepartmentList();
                    int size = departmentList.size();

                    List<DepartmentListResult.DataBean.DepartmentListBean.SecondDepartmentListBean> m2List;
                    for (int i = 0; i <= size; i++) {
                        if (i != 0) {
                            List<DepartmentListResult.DataBean.DepartmentListBean.SecondDepartmentListBean> secondDepartmentList = departmentList.get(i - 1).getSecondDepartmentList();
                            int size2 = secondDepartmentList.size();
                            m2List = new ArrayList<>();
                            DepartmentListResult.DataBean.DepartmentListBean d = new DepartmentListResult.DataBean.DepartmentListBean();
                            d.setDepartmentID(departmentList.get(i - 1).getDepartmentID());
                            d.setDepartmentName(departmentList.get(i - 1).getDepartmentName());
                            for (int j = 0; j <= size2; j++) {
                                if (j == 0) {
                                    DepartmentListResult.DataBean.DepartmentListBean.SecondDepartmentListBean b = new DepartmentListResult.DataBean.DepartmentListBean.SecondDepartmentListBean();
                                    b.setDepartmentID("0");
                                    b.setDepartmentName("全部" + URLDecoderUtil.getDecoder(departmentList.get(i - 1).getDepartmentName()));
                                    m2List.add(b);
                                } else {
                                    m2List.add(secondDepartmentList.get(j - 1));
                                }

                            }
                            d.setSecondDepartmentList(m2List);
                            mFirstList.add(d);
                        }

                    }

                }

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {

            }
        });
    }

}
